package com.weidong.mybbs.exception;

import com.weidong.mybbs.util.AjaxResult;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(value = BusinessException.class)
    @RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity JsonException(BusinessException be, HandlerMethod method,
                                        HttpServletResponse response){
        if (!method.hasMethodAnnotation(ResponseBody.class) && method.getBeanType().getAnnotation(RestController.class) == null){
            try {
                response.setContentType(MediaType.TEXT_HTML_VALUE);
                response.setCharacterEncoding("UTF-8");
                response.sendRedirect("redirect:/error?msg="+ URLEncoder.encode(be.getMessage(),"UTF-8"));
                return null;
            }catch (IOException io){
                return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON_UTF8).body(AjaxResult.error(5000,"服务器错误"));
            }
        }
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(AjaxResult.error(5000,be.getMessage()));
    }
}
